94% completed
Here is the detailed system design for a Distributed Job Scheduler (often called "Distributed Cron").
1. Problem Definition and Scope
We are designing a distributed service that allows applications to schedule tasks to run at specific times or on a recurring schedule. This system acts as a reliable "cloud alarm clock" that triggers other services via HTTP webhooks or message queues when a task is due.
Main User Groups:
-
Developers: They submit job definitions (e.g., "Call my billing API every day at midnight").
-
Admins: They monitor the system to ensure jobs are triggering on time.
Scope:
-
In Scope: Storing job schedules, detecting when a job is due, reliably sending a trigger (HTTP request), and logging the result.
-
Out of Scope: The actual execution of the business logic. We are the scheduler, not the worker. We assume the user provides an API endpoint for us to call. We will not cover complex workflow dependencies (DAGs).
2. Clarify functional requirements
Must Have:
-
Schedule Job: Users can create jobs using standard Cron expressions (e.g., 0 9 * * *) or one-time timestamps.
-
Execute Job: The system triggers a user-defined Webhook (HTTP POST) when the job is due.
-
At-Least-Once Delivery: Jobs must run. In rare failure scenarios, running a job twice is acceptable, but missing it is not.
-
Job Management: CRUD operations (Create, Read, Update, Delete) for jobs.
-
History Logs: Users can view the status (Success/Failure) of past executions.
Nice to Have:
-
Retries: Automatically retry if the webhook returns an error (e.g., HTTP 500).
-
Manual Trigger: Ability to force-run a job immediately for testing.
3. Clarify non-functional requirements
-
Scale: Support 100 million registered jobs.
-
Throughput: Handle 1 million triggers per minute at peak (users often schedule jobs for the top of the hour).
-
Latency: Low drift. The trigger should happen within seconds of the scheduled time.
-
Availability: 99.99%. If the scheduler is down, critical business processes (like backups or payroll) fail.
-
Consistency: Strong consistency for job storage (we cannot lose a scheduled job).
-
Data Retention: Keep execution logs for 30 days.
4. Back of the envelope estimates
- Trigger Traffic (QPS):
- 1,000,000 jobs / 60 seconds
16,600 triggers per second (TPS). - This is the load on the "scan and execute" path.
- 1,000,000 jobs / 60 seconds
- Storage (Job Metadata):
- 100 million jobs.
- Assume 1 KB per job definition.
- 100,000,000 x 1 KB = 100 GB.
- Result: This fits comfortably in a sharded relational database.
- Storage (Execution History):
- 1 million logs/min x 1440 mins/day
1.44 billion logs/day. - At 0.5 KB per log: 1.44 billion x 0.5 KB
720 GB/day. - Result: This is heavy. We generate ~21 TB of logs in 30 days. We need a write-heavy storage solution (like Cassandra or HBase) or aggressive archiving to S3.
- 1 million logs/min x 1440 mins/day
5. API design
We will use a standard REST API.
- POST /v1/jobs
- Request: { "name": "Daily Report", "schedule": "0 9 * * *", "webhook_url": "https://api.app.com/report" }
- Response: 201 Created, { "job_id": "uuid-123" }
- GET /v1/jobs/{job_id}
- Response: Job details, including next_run_at.
- PUT /v1/jobs/{job_id}
- Request: Update schedule or pause the job.
- DELETE /v1/jobs/{job_id}
- Response: 204 No Content.
- GET /v1/jobs/{job_id}/history
- Response: List of { "run_at": "...", "status": "SUCCESS", "response_code": 200 }.
6. High level architecture
We decouple the Scheduler from the Workers.
Client -> Load Balancer -> API Server -> Job Database
Components:
-
API Server: Handles CRUD requests and calculates the initial next_run_at for new jobs.
-
Job Database: The source of truth. Stores job configs and the next scheduled time.
-
Scheduler Cluster: Background servers that partition the database and scan for jobs due "now."
-
Message Queue (Kafka): Acts as a buffer. If 1 million jobs trigger at 9:00 AM, Kafka absorbs the spike so the database doesn't crash.
-
Worker Cluster: Stateless servers that pull tasks from Kafka and send the actual HTTP requests.
-
Coordination Service (ZooKeeper): Assigns database partitions to Scheduler nodes to ensure no two schedulers pick up the same job.
7. Data model
We use a Relational Database (PostgreSQL) for jobs because we need ACID guarantees (locking rows) to prevent double-scheduling.
1. Table: jobs
- id (UUID, PK)
- status (Enum: ACTIVE, PAUSED)
- cron_schedule (String)
- next_run_at (Timestamp, Indexed) — Critical Index.
- partition_id (Integer) — Used for sharding/assignment.
- webhook_url (String)
2. Table: execution_history
- Store: Cassandra or ScyllaDB (optimized for massive write throughput).1
- job_id (Partition Key)
- run_at (Clustering Key, Descending)
- status (SUCCESS, FAILED)
- response_code (Integer)
8. Core flows end to end
This section of the design problem describes the core Operational Pipeline of a distributed job scheduler. It explains the lifecycle of a job from being "at rest" in the database to being "executed" via an HTTP request.
Here is a detailed breakdown of the architecture, the specific mechanics of the flows, and the engineering trade-offs made in this design.
Flow A: The Scheduler Loop (Finding Jobs)
This flow is about Database Partitioning and Coordination.
1. Partitioning & Assignment (Sharding)
The problem mentions dividing jobs into 1,000 logical partitions. This is a sharding strategy to ensure scalability.
-
Why Partition? If you have 1 million jobs, you cannot have one node query SELECT *. It would time out or lock the database.
-
Logical Partitions: A job is likely assigned a partition ID (0-999) based on a hash of its ID (e.g., job_id % 1000).
-
ZooKeeper’s Role: ZooKeeper is used for Cluster Coordination. It acts as the manager. It knows which Scheduler Nodes are alive and distributes the 1,000 partitions among them.
- Scenario: If Node A (handling 0-99) crashes, ZooKeeper detects the heartbeat failure and reassigns partitions 0-99 to Node B. This ensures High Availability.
2. The Scan (Polling)
Each scheduler node runs an infinite loop that wakes up every second.
- The Query:
SELECT * FROM jobs WHERE partition_id BETWEEN 0 AND 99 AND next_run_at <= NOW()
- This query is highly optimized. With an index on (partition_id, next_run_at), the database can fetch the relevant rows almost instantly, even with millions of records.
3. The "Critical Transaction" (Push vs. Update)
This is the most important part of the design regarding data integrity. The system performs two actions:
-
Push: Send the job to the Queue.
-
Update: Change the DB row so it doesn't get picked up again immediately.
The design explicitly chooses to Push first, Update second.
-
The Trade-off: This choice prioritizes Reliability over Exactness.
-
The Failure Scenario (Crash after Push):
- Scheduler reads Job 123 from DB.
- Scheduler pushes Job 123 to Queue (Success).
- CRASH! (Scheduler dies before updating the DB).
- Result: Job 123 is in the Queue (will be executed). But the DB still says Job 123 needs to run right now.
- Recovery: Scheduler restarts, reads Job 123 again, and pushes it to the Queue again.
-
The Outcome: The user receives the webhook twice.
-
The Terminology: This is called At-Least-Once Delivery. In distributed systems, it is generally safer to run a job twice than to lose it completely (which would happen if you Updated DB first, then crashed before Pushing).
Flow B: The Execution (Running Jobs)
This flow deals with Asynchronous Execution and Reliability.
1. Decoupling via Queue
By using a Worker Node to consume from the Queue, the system isolates the scheduling logic from the network logic.
- If the user's webhook takes 30 seconds to respond, the Worker waits, but the Scheduler is free to go back and find more jobs. This prevents head-of-line blocking.
2. Execution & Logs
-
Stateless Workers: The workers don't know the schedule; they just receive a URL and a payload. They execute the POST request.
-
History DB: This implies an "Audit Log" pattern. It separates the "State" (Future jobs) from the "History" (Past jobs). This keeps the main jobs table small and fast.
3. Retry Logic (Handling Failure)
The design handles HTTP 500 errors (Server Errors) using a Retry Topic.
-
Dead Letter/Retry Queues: If a job fails, the Worker doesn't just drop it. It pushes it to a separate queue (or the same queue with a delay metadata).
-
Exponential Backoff: Usually, the "delay" mentioned increases with every failure (e.g., retry in 1 min, then 5 mins, then 1 hour) to avoid spamming a struggling server.
9. Caching and read performance
-
API Caching: We cache job details in Redis (Key: job:{id}) for the API servers. This makes the GET /jobs/{id} endpoint fast and protects the DB from excessive read traffic.
-
Scheduler Caching: We do not cache the scheduler's SELECT query. The Scheduler must see the absolute source of truth in the DB. Using a cache here risks missing jobs or running cancelled jobs. The database index on next_run_at is sufficient for performance.
10. Storage, indexing and media
- Indexes:
- CREATE INDEX idx_scan ON jobs (partition_id, next_run_at).
- This composite index allows the Scheduler to find "jobs in my bucket that are due" instantly, without scanning the whole table.
- Archiving:
- The execution_history grows by 720 GB/day.
- We cannot keep this in hot storage forever.
- Strategy: Run a daily ETL job to move logs older than 7 days to Object Storage (S3) in Parquet format. This is cheap and allows for long-term auditing via tools like Athena, while keeping the main History DB fast.
11. Scaling strategies
How do we handle growth to 100M jobs?
1. Database Sharding
- A single Postgres instance cannot handle 100M rows and high write throughput.
- We physically shard the jobs database by job_id.
- We might have 16 physical DB servers. The partition_id (0-1000) maps to these physical shards.
2. Scheduler Scaling
- Because we use ZooKeeper for assignment, we can simply add more Scheduler Nodes.
- If we scale from 10 to 20 nodes, ZooKeeper detects the new nodes and redistributes the partitions. Each node now has half the work to do.
3. Worker Scaling
- The Worker layer is stateless and decoupled via the Message Queue.
- We use Horizontal Pod Autoscaling (HPA). We monitor the "consumer lag" in Kafka. If the lag increases (tasks are piling up), K8s automatically spins up more Worker pods.
12. Reliability, failure handling and backpressure
- Scheduler Node Failure:
- If a Scheduler Node crashes, it stops sending heartbeats to ZooKeeper.
- ZooKeeper waits for a timeout (e.g., 10s) and reassigns its partitions to other healthy nodes.
- Impact: Jobs in those partitions are delayed by 10s, but never lost.
- Worker Failure:
- If a Worker crashes while processing a job (before acknowledging the message), Kafka will re-deliver the message to another worker after a visibility timeout.
- Circuit Breakers:
- If a user's webhook is down and timing out, our workers could get clogged waiting.
- We implement a Circuit Breaker: if a specific URL fails 10 times in a row, we stop calling it for 5 minutes.
13. Security, privacy and abuse
-
Authentication: All API requests require OAuth2 tokens.
-
Webhook Verification:
- Users need to verify the request came from us. We sign the webhook payload using HMAC-SHA256 and a shared secret. We send the signature in a header X-Scheduler-Signature.
-
SSRF Protection:
- Malicious users might set a webhook URL to http://localhost:8080 or internal IP addresses to scan our network.
- Defense: The Worker must resolve the DNS and block requests to private IP ranges (e.g., 127.0.0.1, 10.0.0.0/8, AWS Metadata IP).
14. Bottlenecks and next steps
- Bottleneck: Database Polling.
- Querying the DB every second is expensive at massive scale.
- Next Step: Implement Hierarchical Timing Wheels in memory. Instead of polling every second, the Scheduler fetches the next 15 minutes of jobs into RAM and manages the countdown locally. This reduces DB load by 99%.
- Bottleneck: Thundering Herd.
- Millions of jobs set to 09:00:00.
- Next Step: Introduce Jitter. Randomly add 0-30 seconds of delay to non-critical jobs to spread the load across the minute.
Summary
-
Decoupled Architecture: Separated Scheduler (finding jobs) and Workers (executing jobs) using a Message Queue.
-
Scalability: Achieved via Database Sharding and Partitioned Scheduling managed by ZooKeeper.
-
Reliability: Guarantees At-Least-Once delivery by pushing to the queue before updating the database schedule.
-
Efficiency: Uses indexes for fast lookups and offloads history to object storage.
On this page
1. Problem Definition and Scope
2. Clarify functional requirements
3. Clarify non-functional requirements
4. Back of the envelope estimates
5. API design
6. High level architecture
7. Data model
8. Core flows end to end
Flow A: The Scheduler Loop (Finding Jobs)
Flow B: The Execution (Running Jobs)
9. Caching and read performance
10. Storage, indexing and media
11. Scaling strategies
12. Reliability, failure handling and backpressure
13. Security, privacy and abuse
14. Bottlenecks and next steps
Summary